#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libpq-fe.h"
#include "time.h"

static void exit_nicely(PGconn *conn){
    PQfinish(conn);
    exit(1);
}


static void testSelect(PGconn *conn){
    PGresult *res;
    int nFields;
    int i, j;

    res = PQexec(conn, "SELECT trade_date,trade_code,open FROM ETF.tradedaily ");
    if(PQresultStatus(res) != PGRES_TUPLES_OK) {
        fprintf(stderr, "FETCH RECORD failed: %s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }

    nFields = PQnfields(res);
    for(i=0; i<nFields; i++)
        printf("%-15s", PQfname(res,i));
    printf("\n");
    
    for(i=0; i<PQntuples(res); i++) {
        for(j=0; j<nFields; j++)
            printf("%-15s", PQgetvalue(res, i, j));
        printf("\n");
    }

    PQclear(res);
}

static void testTruncate(PGconn *conn){
    PGresult *res;
    res = PQexec(conn, "truncate table etf.tradedaily");
    if(PQresultStatus(res) != PGRES_COMMAND_OK) {
        fprintf(stderr, "truncate table failed: %s", PQerrorMessage(conn));
        PQclear(res);
        exit_nicely(conn);
    }
    PQclear(res);
}

static void testInsert(PGconn *conn){
    char sql[] = "INSERT INTO etf.tradedaily(trade_date,trade_code,open) VALUES ($1, $2, $3)";
    const char *stmtName = "stmt";
    PGresult *res;
    char *msg;
    char *paramValues[3];
    int paramLengths[3];
    int paramFormats[3] = {0, 0, 0};
    char tmpStr[10] = {0};

    res = PQprepare(conn, stmtName, sql, 3 , NULL);
    msg = PQresultErrorMessage(res);
    PQclear(res);
    if (strlen(msg) > 0)
    {
        printf("prepared failed/n");
        PQfinish(conn);
        exit(-1);
    }

    for (int i=0; i<10000; i++)
    {
        paramValues[0] = "20231031";
        itoa(i*10,tmpStr,10);
        paramValues[1] = tmpStr;
        itoa(i,tmpStr,10);
        paramValues[2] = tmpStr;
        paramLengths[0] = strlen(paramValues[0]);
        paramLengths[1] = strlen(paramValues[1]);
        paramLengths[2] = strlen(paramValues[2]);
        res = PQexecPrepared(conn,stmtName,3, paramValues, paramLengths, paramFormats, 0);
        msg = PQresultErrorMessage(res);
        PQclear(res);
        if (strlen(msg) > 0)
        {
            printf("execute parepared statement failed at line %d caused by %s \n",i,msg);
        }
    }

}



int main(int argc, char **argv) {
    const char *conninfo;
    PGconn *conn;

    conninfo = "dbname=stock user=stock password=admin1234 host=localhost";
    conn = PQconnectdb(conninfo);
    if(PQstatus(conn) != CONNECTION_OK) {
        fprintf(stderr, "%s", PQerrorMessage(conn));
        exit_nicely(conn);
    }

    time_t start_time=0, end_time=0;

    time(&start_time);
    printf("job start...%ld\n",start_time);
    //testSelect(conn);
    testTruncate(conn);
    testInsert(conn);
    time(&end_time);
    printf("job end...%ld\n",end_time);
    printf("Time Used: %f\n",difftime(end_time,start_time));

    PQfinish(conn);
    return 0;


}